package com.qf.listener;

import com.rabbitmq.client.Channel;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/10/10 8:26
 */
@Component
@RabbitListener(queues = "quene1")
public class Queue2Listener {

    private StringRedisTemplate redisTemplate;
    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void messageHandler(Message msg, String str, Channel channel) throws Exception {
        //1. 获取消息的唯一标识
        long msgId = msg.getMessageProperties().getDeliveryTag();
        //2. 根据消息唯一标识通过setnx命令向redis中存入数据
        if(redisTemplate.opsForValue().setIfAbsent(String.valueOf(msgId),str,5, TimeUnit.SECONDS)){
            //3. 能存入, 直接执行业务, 返回回执
            System.out.println("=======执行了业务, 消费了数据=========" + str);
        }
        //4. 直接返回回执
        channel.basicAck(msgId,true);
    }
}
